#include "SerialPort.h"

SerialPort::SerialPort(QWidget *parent)
    : QWidget(parent)
{
    ui.setupUi(this);
	this->setWindowIcon(QIcon(":/images/images/Qicon.jpg"));
	this->setWindowTitle("小九的串口通信");
	this->m_serialport = new QSerialPort;
	serialport_init();
	QObject::connect(ui.openPushButton, &QPushButton::clicked, this, &SerialPort::open_serialport);
	QObject::connect(ui.sendPushButton, &QPushButton::clicked, this, &SerialPort::send_data);
	QObject::connect(this->m_serialport, &QSerialPort::readyRead, this, &SerialPort::receive_data);

}

SerialPort::~SerialPort()
{}

bool SerialPort::serialport_init()
{
	QList<QSerialPortInfo> serialPortInfoList = QSerialPortInfo::availablePorts();
	if (serialPortInfoList.isEmpty())
	{
		return false;
	}
	QList<QSerialPortInfo>::iterator iter = serialPortInfoList.begin();
	while (iter != serialPortInfoList.end())
	{
		ui.portComboBox->addItem(iter->portName());
		iter++;
	}
	return true;
}

void SerialPort::open_serialport()
{
	if (this->m_serialport->isOpen())
	{
		this->m_serialport->clear();
		this->m_serialport->close();
		ui.label->setStyleSheet("background - color:rgb(255, 0, 0); border-radius:12px;");
		ui.openPushButton->setText("打开串口");
		ui.mainTextEdit->clear();
	}
	else
	{
		this->m_serialport->setPortName(ui.portComboBox->currentText());
		this->m_serialport->open(QIODevice::ReadWrite);
		this->m_serialport->setBaudRate(QSerialPort::Baud9600);				//比特率9600
		this->m_serialport->setDataBits(QSerialPort::Data8);				//数据位8
		this->m_serialport->setParity(QSerialPort::NoParity);				//奇偶校验 无
		this->m_serialport->setStopBits(QSerialPort::OneStop);				//停止位1
		//this->m_serialport->setFlowControl(QSerialPort::NoFlowControl);		//硬件流
		ui.label->setStyleSheet("background - color:rgb(0, 255, 0); border-radius:12px;");
		ui.openPushButton->setText("关闭串口");
	}
}

void SerialPort::send_data()
{
	QString message = ui.msgLineEdit->text();
	QByteArray messageSend;
	messageSend.append(message);
	this->m_serialport->write(messageSend);
}

void SerialPort::receive_data()
{
	QByteArray message;
	message.append(this->m_serialport->readAll());
	ui.mainTextEdit->append(message);
}
